﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Codemonk.Common.Configuring
{
    public class ConfigReader : IConfigReader
    {
        private string configFile;
        public virtual string ConfigFile
        {
            get { return configFile; }
            set
            {
                if (configFile == value) return;
                configFile = value;
            }
        }

        public virtual IEnumerable<string> Read(string xpath)
        {
            return ReadXml(ConfigFile, xpath);
        }

        protected virtual IEnumerable<string> ReadXml(string path, string xpath)
        {
            if (!System.IO.File.Exists(path)) yield return null;
            XmlDocument document = new XmlDocument();
            document.Load(path);
            var collection = document.ReadAll(xpath);
            foreach (var item in collection) yield return item;
        }
        private FileSystemWatcher fileWatcher;

        protected bool enableMonitoring;

        public virtual bool EnableMonitoring
        {
            get { return enableMonitoring; }
            set
            {
                if (enableMonitoring == value) return;
                enableMonitoring = value;
                if (value)
                {
                    fileWatcher = new FileSystemWatcher();
                    var fullpath = System.IO.Path.GetFullPath(ConfigFile);
                    if (!string.IsNullOrWhiteSpace(ConfigFile))
                    {
                        fileWatcher.Path = System.IO.Path.GetDirectoryName(fullpath);
                        fileWatcher.Filter = System.IO.Path.GetFileName(fullpath);
                    }
                    fileWatcher.Changed += fileWatcher_Changed;
                    if (!fileWatcher.EnableRaisingEvents && System.IO.File.Exists(fullpath)) fileWatcher.EnableRaisingEvents = true;
                }
                else
                {
                    if (fileWatcher != null && fileWatcher.EnableRaisingEvents)
                    {
                        fileWatcher.EnableRaisingEvents = false;
                        fileWatcher.Changed -= fileWatcher_Changed;
                        fileWatcher.Dispose();
                    }
                }
            }
        }

        private void fileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            if (OnFileChanged != null) OnFileChanged(this, EventArgs.Empty);
        }

        public event EventHandler OnFileChanged;
    }
}
